import fsPromise from 'fs-promise';

import fs from 'fs';

import installDependencies from '../src/lib/installDependencies';

import Koa from 'koa';
import {exec} from 'child_process';
// @ts-ignore
import colors from 'colors-console';

import configTool from './com/configTool';
import clientMiddleWare from './middleware/clientMiddleWare';
import webSocketTool from './com/webSocketTool/webSocketTool';
import portIsOccupied from './lib/System/portIsOccupied';
import Authentication from './auth/Authentication';
import plugMain from '../plug/plugMain';
import MapResource from './com/MapResource';

import WS from 'ws';
import path from 'path';
import FSTool from './lib/FSTool';


console.log(`============ 程序启动中...${new Date().toLocaleString()} ============`);
const httpAPP = new Koa();

async function main() {
    // cmd命令提示符/批处理/终端 快速编辑模式bug 程序运行被阻塞 顶部标题栏提示选择 需要回车或空格才能继续执行的解决方案...
    exec('reg add HKEY_CURRENT_USER\\Console /v QuickEdit /t REG_DWORD /d 00000000 /f');

    // 初始化运行环境
    const initRes = await configTool.init();
    let endDate = new Date('2028-01-01').toISOString().split('T')[0];
    const serverId = await Authentication.getServerId();
    console.log(colors('cyan', `【服务端设备唯一特征码】：${serverId}`));


    // 开启硬件绑定，并验证外部授权码
    // const resVe: any = await Authentication.Verification();
    // endDate = resVe.endDate;
    // if (new Date() > new Date(resVe.endDate)) {
    //     console.log(colors('red', `============ 授权已过期，请重新授权 ============`));
    //     process.exit();
    // }
    // if (!initRes || !resVe) {
    //     console.log(colors('red', `============ 程序启动失败 ============`));
    //     process.exit();
    // }

    await installDependencies();


    process.on('uncaughtException', async err => {
        console.error('捕获到系统级的崩溃报错！！严重程度为高！，请排查', err && err.stack);
        const logPath = path.join(configTool.appBasePath, '/temp/logs/seriousError/nodeSeriousError.log');
        await fsPromise.ensureDir(path.dirname(logPath));
        const content = `${new Date().toLocaleString()} \n${String(err) + String(err.stack)} \n`;

        FSTool.writeText(logPath, content);
    });


    const httpServerPort = configTool.baseConfig.httpServerPort;

    // 端口占用检测
    if (httpServerPort !== await portIsOccupied(httpServerPort, false)) {
        console.log(colors('red', `============ 端口号 ${httpServerPort} 被占用，程序启动失败 ============`));
        process.exit();
    }


    const ipAddr = configTool.baseConfig.localIPAddress;

    // 【启动 HTTP Web服务器】
    await new Promise((resolve, reject) => {
        const httpServer = httpAPP.listen(httpServerPort, async function () {
            console.log(colors('yellow', `【静态资源网站资源目录】：${configTool.wwwPath}`));

            clientMiddleWare(httpAPP);
            const wss = new WS.Server({server: httpServer});
            webSocketTool.start(wss);

            await plugMain();
            await MapResource.onWatcher();

            console.log(colors('magenta', `【启动 HTTP  Web服务器】：URL:【http://${ipAddr}:${httpServerPort}】，与【WebSocket】共用【${httpServerPort}】端口`));
            console.log(colors('green', `============ 系统启动成功！${configTool.baseConfig.name} 当前版本：${configTool.baseConfig.version} ============`));
            console.log(colors('green', `============ 程序版本日期，2025-10-20 15:24，授权日期至：${endDate} ============`));

            resolve(null);
        });
    });
}

main().then();
